<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="release-idle-container">
                <div class="release-idle-container-title">物品发布</div>
                <div class="release-idle-container-form">
                    <el-input placeholder="请输入二手物品名称" v-model="ProductRequestDto.productName"
                              maxlength="30"
                              show-word-limit>
                    </el-input>
                    <el-input
                        class="release-idle-detiles-text"
                        type="textarea"
                        autosize
                        placeholder="请输入物品的详细介绍..."
                        v-model="ProductRequestDto.description"
                        maxlength="75"
                        show-word-limit>
                    </el-input>
                    <div class="release-tip">物品类别</div>
                    <el-select v-model="ProductRequestDto.categoryId" placeholder="请选择类别">
                        <el-option
                            v-for="item in options2"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                    <div style="margin-top: 10px;">
                        <div class="release-tip">价格</div>
                        <el-input-number v-model="ProductRequestDto.price" :precision="2" :step="5"  :min="0.01" :max="10000000">
                        </el-input-number>
                    </div>
                    <div class="release-idle-container-picture">
                        <div class="release-idle-container-picture-title">上传二手物品照片</div>
                        <el-upload
                            action="http://localhost:8080/products/upload/image"
                            :headers="authHeaders"
                            :on-preview="fileHandlePreview"
                            :on-remove="fileHandleRemove"
                            :on-success="fileHandleSuccess"
                            :show-file-list="showFileList"
                            :limit="2"
                            :on-exceed="handleExceed"
                            accept="image/*"
                            drag
                            multiple>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
                        </el-upload>
                        <div class="picture-list">
                            <el-image style="width: 600px;height:400px; margin-bottom: 2px;" fit="contain"
                                      v-for="(img,index) in imgList" :key="index" :src="img"
                                      :preview-src-list="imgList"></el-image>
                        </div>
                        <el-dialog :visible.sync="imgDialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </div>
                    <div style="display: flex;justify-content: center;margin-top: 30px;margin-bottom: 30px;">
                        <el-button type="primary" plain @click="releaseButton">确认发布</el-button>
                    </div>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'
    import options from '../common/country-data.js'

    export default {
        name: "release",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                imgDialogVisible:false,
                dialogImageUrl:'',
                showFileList:true,
                options:options,
                selectedOptions:[],
                options2: [],//获取分类列表
                imgList:[],
                ProductRequestDto:{
                    productName:'',
                    description:'',
                    images:'',
                    price:0,
                    categoryId:''
                }
            };
        },
        computed: {
            authHeaders() {
                return {
                    Authorization: `Bearer ${window.localStorage.getItem('token')}`
                };
            }
        },
        mounted() {
            this.getCategories();
        },
        methods: {
            //删除图片时触发的方法，更新本地图片列表。
            fileHandleRemove(file, fileList) {
                let urlToRemove = "";
                if (file.response && file.response.data) {
                    urlToRemove = file.response.data;
                } else if (file.url) {
                    urlToRemove = file.url;
                }
                if (urlToRemove) {
                    this.imgList = this.imgList.filter(img => img !== urlToRemove);
                }
            },
            //点击文件列表中的图片时调用的方法，用于预览
            fileHandlePreview(file) {
                if (file.response && file.response.data) {
                    this.dialogImageUrl = file.response.data;
                } else if (file.url) {
                    this.dialogImageUrl = file.url;
                } else if (file.raw) {
                    const reader = new FileReader();
                    reader.readAsDataURL(file.raw);
                    reader.onload = e => {
                        this.dialogImageUrl = e.target.result;
                        this.imgDialogVisible = true;
                    };
                    return; // 这里先return避免重复赋值下面的imgDialogVisible=true
                }
                this.imgDialogVisible = true;
            },
            //上传成功后触发的方法，接收服务器返回的图片 URL。
            fileHandleSuccess(response, file, fileList){
                console.log("file:",response,file,fileList);
                this.imgList.push(response.data);
            },
            releaseButton(){
                this.ProductRequestDto.images=this.imgList;
                // 校验描述是否为空
                if (!this.ProductRequestDto.description || this.ProductRequestDto.description.trim() === '') {
                    this.$message.error('商品描述不能为空');
                    return;
                }
                // 校验描述长度
                if (this.ProductRequestDto.description.length > 75) {
                    this.$message.error('商品描述过多错误');
                    return;
                }
                // 校验图片数量
                if (this.imgList.length < 1) {
                    this.$message.error('请至少上传一张图片');
                    return;
                }
                console.log(this.ProductRequestDto);
                if(this.ProductRequestDto.productName&&
                    this.ProductRequestDto.description&&
                    this.ProductRequestDto.categoryId&&
                    this.ProductRequestDto.price){
                    this.$api.addIdleItem(this.ProductRequestDto).then(res=>{
                        if (res.code === 200) {
                            this.$message({
                                message: '发布成功！',
                                type: 'success'
                            });
                            console.log(res.data);
                            this.$router.replace({path: '/details', query: {productId: res.data.productId}});
                        } else {
                            this.$message.error('发布失败！'+res.msg);
                        }
                    }).catch(e=>{
                        this.$message.error('请填写完整信息');
                    })
                }else {
                    this.$message.error('请填写完整信息！');
                }
            },
            handleExceed(files, fileList) {
                this.$message.error('图片数量超出限制错误');
            }
            ,
            getCategories() {
                this.$api.getAllClassification().then(res => {
                    if (res.code === 200) {
                        this.options2 = res.data.map(item => ({
                            value: item.id,  // 根据后端字段名修改
                            label: item.name
                        }));
                    } else {
                        this.$message.error('获取分类失败：' + res.msg);
                    }
                }).catch(() => {
                    this.$message.error('请求分类接口出错');
                });
            },
        }
    }
</script>

<style scoped>
    .release-idle-container {
        min-height: 85vh;
    }

    .release-idle-container-title {
        font-size: 18px;
        padding: 30px 0;
        font-weight: 600;
        width: 100%;
        text-align: center;
    }

    .release-idle-container-form {
        padding: 0 180px;
    }

    .release-idle-detiles-text {
        margin: 20px 0;
    }
    .release-idle-place{
        margin-bottom: 15px;
    }
    .release-tip{
        color: #555555;
        float: left;
        padding-right: 5px;
        height: 36px;
        line-height: 36px;
        font-size: 14px;
    }
    .release-idle-container-picture{
        width: 500px;
        height: 400px;
        margin: 20px 0;

    }
    .release-idle-container-picture-title{
        margin: 10px 0;
        color: #555555;
        font-size: 14px;
    }
    .picture-list {
        margin: 20px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 100px;
    }
</style>